<template>
  <div>
    <Form ref="formValidate" :model="form" :label-width="120" :rules="ruleValidate">
      <FormItem label="" :label-width="1">
        <Row>
          <i-col span="14">
            <h3>商品基本信息</h3>
          </i-col>
        </Row>

      </FormItem>
      <Row>
        <i-col span="14">
          <FormItem label="所属类目：" prop="categoryIds">
            <Cascader :data="categoryList" @on-change="onCategoryChange" v-model="form.categoryIds"
                      placeholder="点击选择类目"
                      style="width: 300px"></Cascader>
          </FormItem>
        </i-col>

      </Row>
      <Row>
        <i-col span="14">
          <FormItem label="商品属性：">
            <span>{{form.goodsType}}</span>
          </FormItem>
        </i-col>
      </Row>
      <Row>
        <i-col span="14">
          <FormItem label="所属品牌/型号：" prop="brandName">
            <Select v-model="form.brandId" style="width:200px">
              <Option v-for="item in brands" :value="item.value" :key="item.value">{{ item.label }}</Option>
            </Select>
          </FormItem>
        </i-col>
      </Row>

      <Row>
        <i-col span="14">
          <FormItem label="商品标题：" prop="name">
            <Input v-model="form.name" style="width: 88%"></Input>
            <span>(<span style="color: red">0</span>/100)个字符</span>
          </FormItem>
        </i-col>
      </Row>

      <Row>
        <i-col span="14">
          <FormItem label="高亮标签：">
            <Input v-model="form.highLightWord" style="width: 140px"></Input>
            <span>(<span style="color: red">0</span>/4)个字符</span>
          </FormItem>
        </i-col>
      </Row>
      <Row>
        <i-col span="14">
          <FormItem label="特性标签：">
            <InputTag :tags="form.tags" placeholder="输入一个标签后，回车即可输入下一个" style="width: 88%"></InputTag>
          </FormItem>
        </i-col>
      </Row>
      <Row>
        <i-col span="14">
          <FormItem label="商品卖点：">
            <Input v-model="form.shortDesc" type="textarea" :rows="4" placeholder="" style="width:88%"/>
            <p>简短介绍商品主要卖点</p>
          </FormItem>
        </i-col>
      </Row>

      <FormItem label="商品图片：" prop="uploadList">
        <div class="upload-list" v-for="(item,index) in uploadList">
          <div class="upload-list-item">
            <template v-if="item.status === 'finished'">
              <img :src="item.url">
              <div class="upload-list-cover">
                <Icon type="ios-eye-outline" @click.native="handleView(item.url)"></Icon>
                <Icon type="ios-trash-outline" @click.native="handleRemove(item)"></Icon>
              </div>
            </template>
            <template v-else>
              <Progress v-if="item.showProgress" :percent="item.percentage" hide-info></Progress>
            </template>
          </div>
          <div style="text-align: center" v-if="index==0">主图</div>
          <div style="text-align: center" v-else="">详情图</div>
        </div>
        <div class="upload-list">
          <Upload
            ref="upload"
            :show-upload-list="false"
            :default-file-list="defaultList"
            :on-success="handleSuccess"
            :format="['jpg','jpeg','png']"
            :max-size="2048"
            :on-format-error="handleFormatError"
            :on-exceeded-size="handleMaxSize"
            :before-upload="handleBeforeUpload"
            type="drag"
            :action="fileUploadPath"
            style="display: inline-block;width:58px;">
            <div style="width: 58px;height:58px;line-height: 58px;">
              <Icon type="camera" size="20"></Icon>
            </div>
          </Upload>
          <div style="margin-top: -13px;text-align: center">上传图片</div>
        </div>
        <Modal title="查看图片" v-model="visible">
          <img :src="imageUrl" v-if="visible" style="width: 100%">
        </Modal>
      </FormItem>

      <FormItem label="商品属性：" v-if="attrsDefinedList.length>0">
        <Row>
          <i-col span="8" v-for="attr in attrsDefinedList" :key="attr.id">
            <span>{{attr.name}}:</span>
            <!-- 有默认定义列表则用下拉框-->
            <Select v-model="form.attrs[attr.id]" style="width:200px" v-if="attr.options&&attr.options.length>0">
              <Option v-for="item in attr.options" :key="item.id" :value="item.value">{{ item.name }}</Option>
            </Select>
            <template v-else>
              <Input v-model="form.attrs[attr.id]" size="small" style="width: 200px;" placeholder="请填写"></Input>
            </template>
          </i-col>
        </Row>
      </FormItem>

      <FormItem label="商品规格：" v-if="specDefinedList.length>0">
        <Row>
          <i-col span="24" v-for="spec in specDefinedList" :key="spec.id">
            <span>{{spec.name}}:</span>
            <!-- 有默认定义列表则用复选框-->
            <CheckboxGroup v-model="form.specs[spec.id]" v-if="spec.options&&spec.options.length>0"
                           @on-change="renderPriceTableColumn">
              <Checkbox :label="item.name" v-for="item in spec.options"
                        :key="item.id"></Checkbox>
            </CheckboxGroup>
            <template v-else>
              <div>
                <Input v-model="form.specs[spec.id]" size="small" style="width: 200px;" placeholder="请填写"></Input>
              </div>
            </template>
          </i-col>
        </Row>
      </FormItem>
      <!--
            <FormItem label="销售区域：">
              <Row>
                <RadioGroup v-model="form.saleRegion" vertical @on-change="renderPriceTableColumn">
                  <Radio label="ALL">
                    <span>全国统一价</span>
                    <span>价格：</span>
                    <Input v-model="form.originalPrice" style="width:100px" type="number"
                           v-if="form.saleRegion==='ALL'"
                    />
                  </Radio>
                  <Radio label="NOT_ALL">
                    <span>分区域定价</span>
                    <Button type="primary" size="small" @click="showSalesRegionModal"
                            :disabled="form.saleRegion=='all'?'disabled':false">设置可售区域
                    </Button>
                    <span style="color: red" v-if="form.saleRegionList.length==0">(未设置)</span>
                    <span style="color: green" v-else>已选择(<span>{{form.saleRegionList.length}}</span>)个区域</span>
                  </Radio>
                </RadioGroup>
              </Row>
            </FormItem>

            <FormItem label="库存与价格：">
              <Row>
                <i-col span="22" :xs="24" :sm="24" :md="22" :lg="20">
                  <Card dis-hover>
                    &lt;!&ndash;<Row slot="title">
                      <Button type="ghost" size="small">下载价格导入模板</Button>
                      <Button type="primary" size="small">导入价格数据</Button>
                      （<span style="color: red">*</span><span>请先设置可售区域和勾选商品规格，再下载导入模板。</span>）
                    </Row>&ndash;&gt;
                    <Row slot="title">
                      <span>统一设置价格:</span>
                      <Input placeholder="价格" style="width: 100px" v-model="price.price" type="number"/>
                      <Input placeholder="库存" style="width: 100px" v-model="price.stock" type="number"/>
                      <Input placeholder="内部编号" style="width: 100px" v-model="price.number"/>
                      <Input placeholder="内部名称" style="width: 100px" v-model="price.name"/>
                      <Button type="primary" size="small" @click="batchSetPriceData">批量设置</Button>
                      （<span style="color: red">*</span><span>请先设置可售区域和勾选商品规格。</span>）
                    </Row>
                    <Row>
                      <v-table
                        :height="340"
                        is-horizontal-resize
                        style="width:100%"
                        :columns="priceTableColumn"
                        :table-data="priceTableData"
                        row-hover-color="#eee"
                        row-click-color="#edf7ff"
                        :cell-edit-done="cellEditDone"
                      ></v-table>
                    </Row>
                    &lt;!&ndash;<Table height="320" stripe :columns="priceTableColumn" :data="priceTableData"></Table>
                    &ndash;&gt;
                  </Card>
                </i-col>
              </Row>
            </FormItem>

            <FormItem label="商品描述：" prop="detailDesc">
              <Row>
                <i-col span="14">
                  <vue-editor v-model="form.detailDesc"></vue-editor>
                </i-col>
                <i-col span="8" offset="1" style="background-color: #f0f0f0">
                  <div class="phone">
                    <div class="header">
                      <div class="title">商品详情</div>
                    </div>
                    <div class="editor">
                      <div v-html="form.detailDesc"></div>
                    </div>
                  </div>
                </i-col>
              </Row>
            </FormItem>
            <FormItem label="上架时间：">
              <Row>
                <RadioGroup v-model="form.marketable">
                  <Radio label="是">
                    <span>立即上架</span>
                  </Radio>
                  <Radio label="否">
                    <span>放入仓库</span>
                  </Radio>
                </RadioGroup>
              </Row>
            </FormItem>-->

      <Row>
        <i-col span="14">
          <FormItem label="商品描述：">
            <Input v-model="form.detailDesc" type="textarea" :rows="4" placeholder="商品描述......" style="width:88%"/>
            <p>介绍商品详细描述</p>
          </FormItem>
        </i-col>
      </Row>

      <FormItem label="是否为赠品：">
        <Row>
          <RadioGroup v-model="form.gift">
            <Radio :label="1">
              <span>是</span>
            </Radio>
            <Radio :label="0">
              <span>否</span>
            </Radio>
          </RadioGroup>
        </Row>
      </FormItem>

      <FormItem>
        <Button type="primary" @click="handleSubmit('formValidate')" :loading="loading" v-if="!goodsId">发布商品</Button>
        <Button type="primary" @click="handleSubmit('formValidate')" :loading="loading" v-else>提交修改</Button>
        <Button type="ghost" style="margin-left: 8px">取消</Button>
      </FormItem>
    </Form>
    <Modal
      v-model="showSalesRegion"
      title="可售区域设置"
      width="700"
      @on-ok="salesRegionOk">
      <Row type="flex" :gutter="10" style="padding: 5px;">
        <i-col span="18">
          <Tree :data="saleRegionList" show-checkbox @on-check-change="onRegionTreeCheckChange"></Tree>
        </i-col>
      </Row>
    </Modal>
  </div>
</template>

<script>
  import InputTag from "../../utils/InputTag.vue";
  import axios from 'axios';
  import {VueEditor} from 'vue2-editor';
  import 'vue-easytable/libs/themes-base/index.css'
  // 导入 table 组件 和分页组件
  import {VTable, VPagination} from 'vue-easytable'
  import deepExtend from "deep-extend";


  export default {
    components: {
      "InputTag": InputTag,
      "VueEditor": VueEditor,
      "VTable": VTable,
      "VPagination": VPagination,
    },
    data () {
      return {
        form: {
          //商品标题
          name: "",
          //用户选择的品牌下拉框值
          brandId: null,
          //用户选择的类目下拉框值
          categoryIds: [],
          //用户选择的类目ID
          categoryId: null,
          //选择的类目名称
          categoryName: null,
          //商品类型
          goodsType: null,
          //高亮标签
          highLightWord: "",
          //特性标签
          tags: [],
          //商品卖点
          shortDesc: "",
          //商品属性值，用户选择或填写的值，格式为：{属性1id:"属性值1"]}
          attrs: {},
          //用户勾选的商品规格值，格式为： {规格1id:["规格名称1","规格名称1"]}
          specs: {},
          //销售区域方式：全国、分区
          saleRegion: "ALL",
          //销售区域为全国时的统一价
          originalPrice: null,
          //销售区域列表，用户选中的区域列表，只保留最后一级的值
          saleRegionList: [],
          //商品详情
          detailDesc: null,
          //是否立即上架
          marketable: "否",
          //是否为赠品
          gift: 0,
        },
        ruleValidate: {
          name: [
            {required: true, message: '标题不能为空', trigger: 'blur'}
          ],
          categoryIds: [
            {required: true, type: 'array', min: 1, message: '至少选择一个分类', trigger: 'change'},
          ]
        },
        //显示可售区域设置界面
        showSalesRegion: false,
        //可售区域列表，从服务端获取的区域数据，渲染成树状
        saleRegionList: [],
        //可售区域树状组件样式定义
        salesRegionListStyle: {
          width: '300px',
          height: '300px'
        },
        //类目列表，从服务端获取的数据
        categoryList: [],
        //类目下的品牌列表，从服务端获取的数据
        brands: [],
        //商品属性可填可选列表，从服务端获取的数据
        attrsDefinedList: [],
        //商品规格可选列表，从服务端获取的数据
        specDefinedList: [],
        /**
         * 用户选择的规格列表，用于拼装数据提交到服务端，
         * 格式为价格表格数据当中的column定义格式
         */
        userSelectSpecList: [],
        //默认已经上传文件列表，编辑时从服务端获取到的数据
        defaultList: [],
        //点击查看大图时的临时地址
        imageUrl: '',
        visible: false,
        //上传成功的文件列表
        uploadList: [],
        //价格表格列表项
        priceTableColumn: [],
        //价格表格数据
        priceTableData: [],
        //批量设置价格
        price: {
          price: null,
          stock: null,
          number: null,
          name: null,
        },
        //表单提交按钮loading标识
        loading: false,
        fileUploadPath: process.env.CONTEXT + "/file/image",
        goodsId: this.$route.query.goodsId,
        mainImgUrl: this.$route.query.mainImgUrl,
      }
    },
    methods: {
      //初始化
      init () {
        this.getCategoryTypeData();
        //初始化销售区域数据
        axios.post("/areas/find").then(response => {
          //构造一个临时根节点
          response.body.forEach((item) => {
            if (!item.parentId) {
              item.parentId = 0;
            }
            item.expand = true;
            item.title = item.name;
          });
          let parent = {id: 0, name: "根节点"};
          response.body.push(parent);
          this.saleRegionList = this.getTreeData(response.body, parent);
        });
      },
      //构造树结构
      getTreeData (data, parent) {
        let child = [];
        data.forEach((item) => {
          if (item.parentId === parent.id) {
            let o = {
              id: item.id,
              title: item.name,
              parentId: item.parentId,
              attr: item,
              children: [],
              expand: true,
            };
            o.children = this.getTreeData(data, o);
            if (o.children.length == 0) {
              //标识为叶子节点
              o.leaf = true;
            }
            child.push(o);
          }
        });
        return child;
      },
      //销售区域树列表点击时
      onRegionTreeCheckChange (items) {
        this.form.saleRegionList = [];
        items.forEach((item) => {
          //只有叶子节点才加入其中
          if (item.leaf) {
            //将当前item对象当中一个规格对象来处理。
            //增加一个固定的key用于拼装价格列表数据
            item.field = "region";
            //增加一个value属性为便于后面生成表格统一获取该值使用
            item.value = item.title;
            //设置当前区域ID为规格ID
            item.specValueId = item.id;
            this.form.saleRegionList.push(item);
          }
        });
      },
      //获取商品类目数据
      getCategoryTypeData () {
        axios.get("/category/find").then((data) => {
          let parent = null;
          data.body.forEach((item) => {
            if (!item.parentId || item.parentId === null) {
              parent = {
                id: item.id,
                label: item.name,
                value: item.value,
                attr: item,
                parentId: item.parentId,
                children: []
              };
            }
          });
          if (parent) {
            this.categoryList = this.$utils.getTreeData(data.body, parent);
          }
        }, (response) => {
          this.$log.d(response);
          this.$Notice.error({
            title: "系统异常",
            desc: response.message ? response.message : "系统或网络异常"
          });
        });
      },
      //分类下拉框选择事件
      onCategoryChange (selectIds, selectedDatas) {
        if (selectedDatas.length < 1) {
          return;
        }
        let selectedData = selectedDatas[selectedDatas.length - 1].attr;
        let id = selectedData.id;
        this.form.categoryId = id;
        this.form.categoryName = selectedData.name;
        this.form.goodsType = selectedData.goodsType;
        //清空已经选择和录入的数据
        this.form.brandName = "";
        this.form.attrs = {};
        this.form.specs = {};
        //查询分类下的品牌和规格、属性
        axios.get("/category/findByCategoryId/" + id).then((response) => {
          let data = response.body;
          this.brands = data.brands;
          this.attrsDefinedList = data.attrs;
          this.specDefinedList = data.specs;
        }, (response) => {
          this.$log.d(response);
          this.$Notice.error({
            title: "系统异常",
            desc: response.message ? response.message : "系统或网络异常"
          });
        });
      },
      //可售区域界面保存事件
      salesRegionOk () {
        this.showSalesRegion = false;
        //修改价格列表
        this.renderPriceTableColumn();
      },
      //显示设置可售区域
      showSalesRegionModal () {
        this.showSalesRegion = true;
      },
      //渲染价格列表列项，根据用户选择的规格、可售区域动态生成
      renderPriceTableColumn () {
        this.$log.d("重新渲染价格列表");
        this.userSelectSpecList = [];
        let columns = [];
        for (let specId in this.form.specs) {
          let specOptionValues = this.form.specs[specId];
          //根据specId查找Spec的规格当列显示的值
          let specItem = this.findSpecValue(specId);
          //只有当前规格下有被选中的规格值才加入列当中
          if (specOptionValues.length > 0) {
            //compute:"condition" 为条件列，渲染数据时，对条件列进行笛卡尔乘积计算
            let c = {
              title: specItem.name,
              field: "spec" + specId,
              specId: specId,
              width: 80,
              isResize: true,
              compute: "condition"
            };
            //获取用户勾选的选项值，拼装好需要的属性，便于后续使用
            let selectOptions = [];
            specOptionValues.forEach((item) => {
              let o = this.findSpecOptionValue(item);
              if (o) {
                o.field = c.field;
                selectOptions.push(o);
              }
            });
            c.options = selectOptions;
            columns.push(c);
          }
        }
        //选择为分区域定价
        if (this.form.saleRegion === "NOT_ALL") {
          let c = {
            title: "销售区域",
            width: 120,
            isResize: true,
            field: "region",
            compute: "condition",
            options: this.form.saleRegionList
          };
          columns.push(c);
        }
        columns.push({title: "价格", width: 80, field: "price", compute: "result", isEdit: true, isResize: true});
        columns.push({title: "库存", width: 80, field: "stock", compute: "result", isEdit: true, isResize: true});
        columns.push({title: "内部编号", width: 80, field: "sn", compute: "result", isEdit: true, isResize: true});
        columns.push({title: "内部名称", width: 80, field: "name", compute: "result", isEdit: true, isResize: true});
        this.priceTableColumn = columns;
        //预先渲染数据项目
        this.renderPriceTableData();
      },
      //编辑当前选择的列数据
      cellEditDone (newValue, oldValue, rowIndex, rowData, field) {
        let o = this.priceTableData[rowIndex];
        o[field] = newValue;
        this.$set(this.priceTableData, rowIndex, o);
      },
      //查找规格ID对应的值
      findSpecValue (specId) {
        for (let spec of this.specDefinedList) {
          if (spec.id === specId * 1) {
            return spec;
          }
        }
        this.$log.d("未找到对应的spec,specId:%o", specId);
        return null;
      },
      //查找属性ID对应的值
      findAttrValue (attrId) {
        for (let attr of this.attrsDefinedList) {
          if (attr.id === attrId * 1) {
            return attr;
          }
        }
        this.$log.d("未找到对应的attr,attrId:%o", attrId);
        return null;
      },
      //根据规格值的ID查找规格值对象
      findSpecOptionValue (specOptionValue) {
        for (let spec of this.specDefinedList) {
          let options = spec.options || [];
          for (let option of options) {
            if (option["name"] === specOptionValue) {
              //拼成一个用于提交到后端的对象格式
              option["specValueId"] = option.id;
              //所属规格ID
              option["specId"] = spec.id;
              return option
            }
          }
        }
        this.$log.d("未找到对应的specOption,specOptionValue:%o", specOptionValue);
        return null;
      },
      //预先根据用户勾选的规格和销售区域设置价格列表
      renderPriceTableData () {
        //计算列字段数组
        let computeArray = [];
        //结果列字段数组
        let resultArray = [];
        this.priceTableColumn.forEach((item) => {
          if (item.compute === "condition") {
            computeArray.push(item.options);
          } else {
            resultArray.push(item);
          }
        });
        this.$log.d("computeArray:%o", computeArray);
        //组合所有计算条件列的数组
        let result = this.computeConditionColumn(computeArray);
        let priceTableData = [];
        result.forEach((item) => {
          //每个item为具体的规格值列表（一个option对象）
          let d = {};
          //拼装好需要传到后台的数据格式
          let specValueFullPathValue = [];
          let specValueFullPathName = [];
          let specValueFullPathFieldName = [];
          item.forEach((a) => {
            d[a.field] = a.name;
            specValueFullPathValue.push(a.value);
            specValueFullPathName.push(a.name);
            specValueFullPathFieldName.push(a.field);
          });
          d.specValueFullPathValue = specValueFullPathValue.join("/");
          d.specValueFullPathName = specValueFullPathName.join("/");
          d.specValueFullPathFieldName = specValueFullPathFieldName.join("/");
          resultArray.forEach((a) => {
            d[a.field] = null;
          });
          priceTableData.push(d);
        });
        this.priceTableData = priceTableData;
      },
      //使用笛卡尔算法，计算所有规格和销售区域的数组值
      computeConditionColumn (allArray) {
        let result = [];//结果保存到这个数组
        function toResult (arrIndex, aresult) {
          if (arrIndex >= allArray.length) {
            result.push(aresult);
            return;
          }
          let aArr = allArray[arrIndex];
          if (!aresult) aresult = [];
          for (let i = 0; i < aArr.length; i++) {
            let theResult = aresult.slice(0, aresult.length);
            theResult.push(aArr[i]);
            toResult(arrIndex + 1, theResult);
          }
        }

        toResult(0);
        return result;
      },
      //批量设置价格和库存
      batchSetPriceData () {
        let data = deepExtend({}, {array: this.priceTableData});
        data.array.forEach((item) => {
          item.price = this.price.price;
          item.stock = this.price.stock;
          item.number = this.price.number;
          item.name = this.price.name;
        });
        this.priceTableData = data.array;
      },
      //大图方式查看上传的图片
      handleView (url) {
        this.imageUrl = url;
        this.visible = true;
      },
      //删除已经上传的文件
      handleRemove (file) {
        // 从 upload 实例删除数据
        this.$Modal.confirm({
          "title": "删除图片",
          content: "确认删除吗？", onOk: () => {
            const fileList = this.$refs.upload.fileList;
            this.$refs.upload.fileList.splice(fileList.indexOf(file), 1);
          }
        });
      },
      //表单提交
      handleSubmit (name) {
        this.$refs[name].validate((valid) => {
          if (valid) {
            //校验图片数量
            if (this.uploadList.length < 2) {
              this.$Notice.error({"title": "提交失败", "desc": "至少上传两张图片"});
              return;
            }
            //商品规格必选
            /*let hasSelect = false;
             for (let specId in this.form.specs) {
             hasSelect = true;
             }
             if (!hasSelect) {
             this.$Notice.error({"title": "提交失败", "desc": "必须勾选"});
             return;
             }*/
            if (this.form.saleRegion === "NOT_ALL" && this.saleRegionList.length == 0) {
              this.$Notice.error({"title": "提交失败", "desc": "销售区域列表不能为空"});
              return;
            }

            //todo 校验每个价格的数据格式

            if (this.form.saleRegion === "NOT_ALL") {
              //校验价格列表
              if (this.priceTableData.length < 1) {
                this.$Notice.error({"title": "提交失败", "desc": "必须设置库存与价格"});
                return;
              }
              this.form.originalPrice = null;
              let hasError = false;
              this.priceTableData.forEach((d) => {
                if (!d.price) {
                  hasError = true;
                }
              });
              if (hasError) {
                this.$Notice.error({"title": "提交失败", "desc": "商品价格不能为空"});
                return;
              }
            }

            //校验商品详情
            if (!this.form.detailDesc) {
              this.$Notice.error({"title": "提交失败", "desc": "必须填写商品详情"});
              return;
            }
            //组装表单提交数据
            let form = deepExtend({}, this.form);
            //获取品牌名称
            for (let b of this.brands) {
              if (b.value === form.brandId) {
                form.brandName = b.label;
                break;
              }
            }
            form.tags = this.form.tags.join(",");
            //用户勾选过的规格列表以及对应的规格值列表
            form.goodsSpecOptions = [];
            this.priceTableColumn.forEach((c) => {
              //只有为条件的列，才加入到规格列表当中。排除销售区域
              if (c.compute === "condition" && c.field !== "region") {
                form.goodsSpecOptions.push({specId: c.specId, options: c.options});
              }
            });
            //用户勾选的属性列表以及对应的属性值
            form.goodsAttrOptions = [];
            for (let attrId in this.form.attrs) {
              let value = this.form.attrs[attrId];
              //查找attrId对应的属性名称
              let attr = this.findAttrValue(attrId);
              form.goodsAttrOptions.push({attrId: attrId, attrValue: value, attrName: attr.name});
            }
            //价格列表
            form.goodsSalesSpecOptions = this.priceTableData;
            //图片地址
            let mainImgUrls = [];
            this.uploadList.forEach((item) => {
              mainImgUrls.push(item.url);
            });
            form.mainImgUrl = mainImgUrls.join(",");
            this.loading = true;
            axios.post("/goodsInfo/save", form).then((response) => {
              this.$Message.success('提交成功!');
              this.loading = false;
            }, (response) => {
              this.loading = false;
              this.$log.d(response);
              this.$Notice.error({
                title: "系统异常",
                desc: response.message ? response.message : "系统或网络异常"
              });
            })
          } else {
            this.$Notice.error({"title": "提交失败", "desc": "表单验证失败，请检查是否有部分内容填写不正确"})
          }
        })
      },
      handleSuccess (res, file) {
        // 因为上传过程为实例，这里模拟添加 url
        file.url = res.url;
        file.name = res.name;
      },
      handleFormatError (file) {
        this.$Notice.warning({
          title: '文件格式不正确',
          desc: '文件 ' + file.name + ' 格式不正确，请上传 jpg 或 png 格式的图片。'
        });
      },
      handleMaxSize (file) {
        this.$Notice.warning({
          title: '超出文件大小限制',
          desc: '文件 ' + file.name + ' 太大，不能超过 2M。'
        });
      },
      handleBeforeUpload () {
        const check = this.uploadList.length < 5;
        if (!check) {
          this.$Notice.warning({
            title: '最多只能上传 5 张图片。'
          });
        }
        return check;
      },
      updateLoadData () {
        if (this.goodsId) {
          this.uploadList = [];
          this.$axios.post("/goodsInfo/" + this.goodsId).then((response) => {
            let responseBody = response.body;
            this.form = this.$deepExtend({}, responseBody);
            this.form.tags = responseBody.tags ? responseBody.tags.split(",") : [];
            this.form.categoryIds = [responseBody.categoryId];
            console.log(responseBody);
            let imgUrls = responseBody.mainImgUrl.split(",");
            imgUrls.forEach(img => {
              this.uploadList.push({url: img, status: "finished"});
            });
            this.loading = false;
          }, (response) => {
            this.loading = false;
            this.$log.d(response);
            this.$Notice.error({
              title: "系统异常",
              desc: response.message ? response.message : "系统或网络异常"
            });
          })
        }
      }
    },
    created () {
      this.updateLoadData();
    },
    mounted () {
      this.uploadList = this.$refs.upload.fileList;
      this.init();
    }
  }
</script>
<style scoped>
  a {
    color: #3778ff;
    margin-left: 1.5rem;
  }

  .upload-list {
    display: inline-block;
  }

  .upload-list-item {
    width: 60px;
    height: 60px;
    overflow: hidden;
    text-align: center;
    border: 1px solid transparent;
    border-radius: 4px;
    background: #fff;
    position: relative;
    box-shadow: 0 1px 1px rgba(0, 0, 0, .2);
    margin-right: 4px;
  }

  .upload-list img {
    width: 100%;
    height: 100%;
  }

  .upload-list-cover {
    display: none;
    position: absolute;
    top: 0;
    bottom: 0;
    left: 0;
    right: 0;
    background: rgba(0, 0, 0, .6);
  }

  .upload-list-item:hover .upload-list-cover {
    display: block;
  }

  .upload-list-cover i {
    color: #fff;
    font-size: 20px;
    cursor: pointer;
    margin: 18px 2px;
  }

  /*模拟手机*/
  .phone {
    margin: 5px auto;
    border-radius: 35px;
    background-color: #fff;
    width: 326px;
    height: 620px;
    position: relative;
  }

  .phone .title {
    color: white;
    font-size: 18px;
    width: 100%;
    height: 100%;
    text-align: center;
    margin-top: 23px;
  }

  .phone .header {
    position: absolute;
    left: 3px;
    top: 37px;
    right: 3px;
    height: 60px;
    background-image: url();
  }

  .phone .editor {
    position: absolute;
    top: 89px;
    left: 4px;
    right: 3px;
    height: 486px;
  }
</style>
<style>
  #quill-container {
    height: 579px;
  }
</style>
